#!/usr/bin/env python
# ~/projects/QKmach/app.py
#coding=utf-8
#encoding=utf-8

import os
import string
import json
import datetime
from flask import Flask
from flask import render_template
from flask import request
import MySQLdb
import ConfigParser #解析配置文件
import notice

#初始化********************************************************************
app = Flask(__name__)
mysqlcf = ConfigParser.ConfigParser()
mysqlcf.read('linkmysql.ini') #mysql 配置文件
mysqlhost = mysqlcf.get('recodb','host')
mysqlport = string.atoi(mysqlcf.get('recodb','port'))
mysqluser = mysqlcf.get('recodb','user')
mysqlpasswd = mysqlcf.get('recodb','psw')
mysqldb = mysqlcf.get('recodb','db')
recodb = MySQLdb.connect(host=mysqlhost,port=mysqlport,user=mysqluser,passwd=mysqlpasswd,db=mysqldb)

def myconverter(o):    #datetime类型的数据转json时需要进行处理
    if isinstance(o, datetime.datetime):
        return o.__str__()

def init_inform(): #发通知给bearychat机器人
    startmsg = "乾坤机已启动，信息"    
    imgurl=[{"images":[{"url":"http://static.open-open.com/lib/uploadImg/20160901/20160901163347_878.png"}]}]
    notice.sendmsg(startmsg,imgurl) 

#功能服务******************************************************************
##用户管理
def user_register(userid,username,userpswd):
    #新增用户，数据类型为“用户”，业务类型为“系统管理”
    #初始化密码，存储在属性passwd的值中，数据类型为用户，业务类型为系统管理。

##管理组织
##1组织注册

##2组织核查

##管理项目
##1项目注册

##2项目核查

##管理令牌
##1令牌注册
def token_register(tokenid,tokenname):
      pass
##2令牌核查

##权限管理
##1用户密码验证
def valid_login(usnm,pswd):
    if usnm == 'git' and pswd ==  'git':
        return True
    else:
        return False
##2验证权限

#数据服务******************************************************************
@app.route('/mysql/do/<sqlstr>')
def sqldo(sqlstr):
    sqlstring = sqlstr[1:-1]
    print (sqlstring)
    cur = recodb.cursor()
    print (cur)
    cur.execute(sqlstring)
    recodb.commit()
    return sqlstring

@app.route('/mysql/query/<sqlstr>')
def sqlquery(sqlstr):
    sqlstring = sqlstr[1:-1]
    cur = recodb.cursor()
    cur.execute(sqlstring)
    results = cur.fetchall()
    rows = []
    for r in results:
        rl = list(r)
        print (r[0])
        rows.append(rl)
    replytb = {'data':rows}
    print (replytb)
    return json.dumps(replytb,default=myconverter)

@app.route('/mysql/cmd')
#通过post表单传递字段名和字段值

@app.route('/getQKdata')
def get_server_data():
    results = {"data":[[1,1,'a','atype','atype','2017'],[1,1,'b','btype','btype','2017']]}
    return json.dumps(results)

#请求服务******************************************************************
##登录验证
@app.route('/login',methods=['POST','GET'])
def login():
    erro = None
    print request.form['username']
    print request.form['password']
    if valid_login(request.form['username'],request.form['password']):
        return request.form['username'] + u",你好！"
    else:
        return request.form['username'] +  u" 用户或密码错误，访问！！"

##欢迎页
@app.route('/')
def QKmach():
    return 'Welcome to 乾坤机！'

@app.route('/hello/')
@app.route('/hello/<name>')
def hello(name=None):
    return render_template('hello.html', name=name)

@app.route('/mes/')
@app.route('/mes/<name>')
def mes(name=None):
    return render_template('mes.html', name=name)

@app.route('/index/')
@app.route('/index/<name>')
def index(name=None):
    return render_template('index.html', name=name)

@app.route('/apidoc/')
@app.route('/index/<name>')
def index(name=None):
    return render_template('/home/pi/projects/apidoc/index.html', name=name)

##用户交互
@app.route('/dtables')
def dtables():
     fields = ['父编码'.decode('utf-8'),'编码'.decode('utf-8'),'描述'.decode('utf-8'),'数据类型'.decode('utf-8'),'业务类型'.decode('utf-8'),'创建时间'.decode('utf-8')]
     return render_template('qkdt.html', fields=fields)

#调试方法**********************************************************
def monitor_template():
    from os import path
    extra_dirs = ['templates',]
    extra_files = extra_dirs[:]
    for extra_dir in extra_dirs:
        for dirname, dirs, files in os.walk(extra_dir):
            for filename in files:
                filename = path.join(dirname, filename)
                if path.isfile(filename):
                    extra_files.append(filename)
    return extra_files

if __name__ == '__main__':
    init_inform()
    app.run(debug=False,host='0.0.0.0',port=5000,extra_files=monitor_template())
